package networking;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;


public class SnakeServer 
{
	private static int PORT = 5676;
    private ArrayList<ClientThread> clients = new ArrayList<ClientThread>();
	
	public static void main(String[] args) 
	{
		new SnakeServer();
	}
	
	public SnakeServer()
	{
		
		try
		{
			ServerSocket server = new ServerSocket(PORT);
			System.out.println("Server Started");
			while(true)
			{
				Socket socket = server.accept();
				ClientThread client = new ClientThread(socket, clients);
				Thread thread = new Thread(client);
				clients.add(client);
				thread.start();
			}
		}
		catch(IOException ex)
		{
			System.err.println(ex);
	    }
	}

	public static String[] getHighScores() 
	{
		//TODO get highscores from text file and put them in a string[]
		return null;
	}

	public static void addHighScore(String score) 
	{
		// TODO add score to text file
		
	}

	public static String addMap(SMap map) 
	{
		BufferedImage image = new BufferedImage(map.getWidth(), map.getHeight(), BufferedImage.TYPE_INT_RGB);
		for(int i=0; i<map.getHeight(); i++)
		{
			for(int j=0; j<map.getWidth(); j++)
			{
				image.setRGB(j, i, map.getValue(i, j)); 
			}
		}
		
		File outputFile = new File("custom/"+map.getTitle()+".snake");
		try 
		{
			ImageOutputStream iOS = ImageIO.createImageOutputStream(outputFile);
			if(!ImageIO.write(image, "png", iOS))
			{
				System.out.println("no appropriate writer found");
			}
			iOS.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			return ("Map not written");
		}
		System.out.println("Saved "+map.getTitle()+".snake");
		return "Map Saved Successfully";
		
	}

	public static ArrayList<SMap> getMaps() 
	{
		// TODO read all custom maps and put them in arraylist
		int maps = 0;
		File folder = new File("custom/");
		File[] fileArray = folder.listFiles();
		maps = fileArray.length;
		ArrayList<SMap> list = new ArrayList<SMap>();
		for (int i = 0; i < maps; i++) 
		{
			String file = fileArray[i].getAbsolutePath();
			if(file.endsWith(".snake"))
			{
				System.out.println("Test: " +file);
				File inputFile = new File(file);
				BufferedImage b;
				try
				{
					b = ImageIO.read(inputFile);
					
					int[][] m = new int[b.getWidth()][b.getHeight()];
					for(int k=0; k<b.getWidth(); k++)
					{
						for(int j=0; j<b.getHeight(); j++)
						{
							m[k][j] = b.getRGB(k, j);
						}
					}
					list.add(new SMap(m, inputFile.getName()));
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
					System.exit(0);
				}
			}
		}
		return list;
	}

}
